package com.xiaobaibai.controller;

import com.alibaba.fastjson.JSON;
import com.xiaobaibai.common.Common;
import com.xiaobaibai.common.TokenCommon;
import com.xiaobaibai.common.response.ResponseFormat;
import com.xiaobaibai.pojo.Comment;
import com.xiaobaibai.pojo.User;
import com.xiaobaibai.pojo.UserAdmin;
import com.xiaobaibai.server.user.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.security.Principal;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

//    @PostMapping("/login")//被security取代
    public ResponseFormat login(HttpServletRequest request) throws  IOException {

        Map<String,String> data = (Map<String, String>) request.getAttribute("loginData");
        log.info("登录请求:"+ data);
        String token = userService.login(data.get("username"),data.get("password"));

        return ResponseFormat.createSuccessResponse("登录成功",token);
    }

    @GetMapping("/getUserInfo")
    public ResponseFormat getUserInfo(Principal principal){
//        这种也可以
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        String name = authentication.getName();
//        log.info(name);

        //还是喜欢在参数里面的
        String name=principal.getName().substring(1,principal.getName().length()-1);

        UserAdmin userAdmin = userService.getUserInfo(name);

        userAdmin.setName("小白白");
        userAdmin.setAvatar("http://image.xiaobaibai.ink/%E7%B4%A0%E6%8B%93.png");
        userAdmin.setIntroduction("管理员白白");

        return ResponseFormat.createSuccessResponse("获取用户信息成功",userAdmin);
    }

    /**
     * 用户管理页面获取用户信息
     * @return ResponseFormat
     */
    @GetMapping("/getUserList")
    public ResponseFormat getUserList(){
        List<User> userList = userService.getUserList();
        return ResponseFormat.createSuccessResponse("查询用户列表成功",userList);
    }

    @PostMapping("/welcomeNewUser")
    public ResponseFormat welcomeNewUser(@RequestParam("id") String id){
        userService.welcomeNewUser(id);
        return ResponseFormat.createSuccessResponseOnlyMessage("欢迎完毕~");
    }

    @PostMapping("/delUser")
    public ResponseFormat delUser(@RequestParam("id") String id){
        log.info("删除用户->id:"+id);
        userService.delUser(id);
        return ResponseFormat.createSuccessResponseOnlyMessage("已删除");
    }

}
